<template>
  <div class="admin-container">
    <h1>用户列表</h1>
    <el-button type="warning" @click="logout" class="logout-btn">退出登录</el-button>
    <el-card>
      <el-table :data="userList" border>
        <el-table-column prop="user_id" label="ID"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column prop="phone" label="电话号码"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button type="danger" @click="deleteUser(row.user_id)">删除</el-button>
            <el-button @click="openEditDialog(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增编辑对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑用户" width="30%">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="editForm.password" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="editForm.phone" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">确认</el-button>
          </span>
        </template>
      </el-dialog>

    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'

const userList = ref([])
const editDialogVisible = ref(false)
const editForm = ref({
  user_id: null,
  email: '',
  phone: '',
  password: '',
  username: ''
})


const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除本地存储的token
    localStorage.removeItem('adminToken')
    // 跳转到登录页
    window.location.href = '/login' // 根据实际路由调整
    ElMessage.success('退出成功')
  }).catch(() => {})
}

// 打开编辑对话框c
const openEditDialog = (user) => {
  editForm.value = {
    userId: user.user_id,
    email: user.email,
    phone: user.phone,
    password: user.password,
    username: user.username
  }
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    await axios.put(`${BASE_URL}/admin/users/${editForm.value.userId}`, {
      email: editForm.value.email,
      phone: editForm.value.phone,
      password: editForm.value.password,
      username: editForm.value.username
    }, {
      headers: { Authorization: `Bearer ${localStorage.getItem('adminToken')}` }
    })

    ElMessage.success('更新成功')
    editDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await axios.get(BASE_URL + '/admin/users', {
      headers: { Authorization: `Bearer ${localStorage.getItem('adminToken')}` }
    })
    userList.value = response.data.data || []
  } catch (error) {
    ElMessage.error('获取用户失败')
    userList.value = [] // 确保数据为数组类型
  }
}

// 删除用户
const deleteUser = async (userId) => {
  try {
    await axios.delete(`${BASE_URL}/admin/users/${userId}`)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.logout-btn {
  margin-right: 20px;
}
</style>